<template>
  <div class="bill-preview-page">
    <van-nav-bar
      :title="'订单账单'"
      left-arrow
      @click-left="router.back()"
    />
    
    <div class="bill-preview" v-if="order">
      <div class="preview-content">
        <div class="order-info">
          <div class="order-header">
            <span>订单号: {{ order.id }}</span>
            <span class="order-time">{{ order.time }}</span>
          </div>
          <div class="products-list">
            <div v-for="(product, index) in order.products" :key="index" class="product-row">
              <span class="product-name">{{ product.name }}</span>
              <span class="product-quantity">x{{ product.quantity }}</span>
              <div class="product-price-wrapper">
                <van-field 
                  v-if="editingProductId === product.id"
                  v-model="editPrice"
                  type="digit"
                  input-align="right"
                  class="price-input"
                  @blur="savePrice(product)"
                  @keyup.enter="savePrice(product)"
                  autofocus
                  :maxlength="10"
                />
                <span v-else class="product-price" @click="startEdit(product)">
                  ¥{{ product.price.toFixed(2) }}
                </span>
              </div>
            </div>
          </div>
          <!-- 价格调整记录 -->
          <div v-if="order.priceAdjustments && order.priceAdjustments.length > 0" class="price-adjustments">
            <div class="section-title">价格调整</div>
            <div class="adjustments-list">
              <div v-for="(adjustment, index) in order.priceAdjustments" :key="index" class="adjustment-row">
                <span class="product-name">{{ adjustment.productName }}</span>
                <span class="adjustment-details">¥{{ adjustment.originalPrice?.toFixed(2) || '0' }} → ¥{{ adjustment.newPrice?.toFixed(2) || '0' }}</span>
                <span :class="['difference', (adjustment.difference || 0) >= 0 ? 'price-increase' : 'price-decrease']">
                  {{ (adjustment.difference || 0) >= 0 ? '+' : '' }}¥{{ (adjustment.difference || 0).toFixed(2) }}
                </span>
              </div>
            </div>
          </div>
          <div class="order-total">
            <span>总计：</span>
            <span class="total-amount">¥{{ order.totalAmount.toFixed(2) }}</span>
          </div>
        </div>
        
      </div>
      <div class="preview-footer">
        <van-button type="primary" block @click="printBill">打印账单</van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'

// 定义类型
interface Product {
  id: number;
  name: string;
  quantity: number;
  price: number;
  originalPrice?: number;
}

interface Order {
  id: number;
  customerId: number;
  customerName: string;
  customerAvatar: string;
  date: string;
  time: string;
  products: Product[];
  totalAmount: number;
  status: 'pending' | 'completed';
  priceAdjustments?: {
    productId: number;
    productName: string;
    originalPrice: number;
    newPrice: number;
    quantity: number;
    difference: number;
  }[];
}

const router = useRouter()
const route = useRoute()
const orderId = Number(route.params.id)
const order = ref<Order | null>(null)

// 直接价格编辑相关
const editingProductId = ref<number | null>(null)
const editPrice = ref('')

// 获取订单详情
const fetchOrderDetail = () => {
  // 这里应该是从API获取数据
  // 暂时模拟数据
  order.value = {
    id: orderId,
    customerId: 1,
    customerName: '张大姐',
    customerAvatar: '/avatars/1.png',
    date: '2024-01-20',
    time: '14:30',
    products: [
      { id: 1, name: '康师傅红烧牛肉面', quantity: 2, price: 4.5 },
      { id: 2, name: '统一老坛酸菜面', quantity: 1, price: 4.0 },
      { id: 3, name: '雪碧', quantity: 1, price: 3.0 }
    ],
    totalAmount: 16.0,
    status: 'pending',
    priceAdjustments: []
  }
}

// 开始编辑价格
const startEdit = (product: Product) => {
  editingProductId.value = product.id
  editPrice.value = product.price.toString()
}

// 保存价格修改
const savePrice = (product: Product) => {
  if (!order.value) return
  
  const newPriceValue = Number(editPrice.value)
  
  if (isNaN(newPriceValue) || newPriceValue <= 0) {
    showToast({
      type: 'fail',
      message: '请输入有效的价格'
    })
    editingProductId.value = null
    return
  }
  
  // 价格没有变化，不做处理
  if (newPriceValue === product.price) {
    editingProductId.value = null
    return
  }
  
  // 记录原价
  if (!product.originalPrice) {
    product.originalPrice = product.price
  }
  
  // 计算差额
  const originalPrice = product.originalPrice
  const difference = (newPriceValue - originalPrice) * product.quantity
  
  // 更新价格
  product.price = newPriceValue
  
  // 更新订单总金额
  recalculateOrderTotal()
  
  // 添加或更新价格调整记录
  if (!order.value.priceAdjustments) {
    order.value.priceAdjustments = []
  }
  
  const existingAdjustment = order.value.priceAdjustments.find(adj => adj.productId === product.id)
  
  if (existingAdjustment) {
    existingAdjustment.newPrice = newPriceValue
    existingAdjustment.difference = difference
  } else {
    order.value.priceAdjustments.push({
      productId: product.id,
      productName: product.name,
      originalPrice: originalPrice,
      newPrice: newPriceValue,
      quantity: product.quantity,
      difference: difference
    })
  }
  
  showToast({
    type: 'success',
    message: '价格已更新'
  })
  
  editingProductId.value = null
}

// 重新计算订单总金额
const recalculateOrderTotal = () => {
  if (!order.value) return
  
  order.value.totalAmount = order.value.products.reduce((total, product) => {
    return total + (product.price * product.quantity)
  }, 0)
}

// 打印账单
const printBill = () => {
  showToast({
    type: 'loading',
    message: '正在打印...',
    forbidClick: true
  })
  
  setTimeout(() => {
    showToast({
      type: 'success',
      message: '打印成功'
    })
    
    // 返回结算页并移除对应订单
    setTimeout(() => {
      router.push('/settlement')
    }, 500)
  }, 1500)
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style lang="scss" scoped>
.bill-preview-page {
  min-height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.bill-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
  background: #fff;
  margin: 15px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .preview-content {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 20px;
    
    .order-info {
      .order-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #f5f5f5;
        font-size: 14px;
        color: #666;
      }
    }

    .products-list {
      margin-bottom: 20px;

      .product-row {
        display: grid;
        grid-template-columns: 2fr 1fr 1fr;
        font-size: 14px;
        padding: 12px 0;
        border-bottom: 1px dashed #f5f5f5;

        .product-price-wrapper {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          
          .product-price {
            font-weight: 500;
            cursor: pointer;
            color: #1989fa;
            text-decoration: underline;
            text-decoration-style: dotted;
          }
          
          .price-input {
            font-weight: 500;
            width: 80px;
            padding: 0;
            margin-right: 0;
            
            &::v-deep(.van-field__control) {
              text-align: right;
              font-weight: 500;
              color: #1989fa;
            }
          }
        }
        
        .product-quantity {
          text-align: center;
        }
      }
    }

    .price-adjustments {
      margin-top: 15px;
      padding: 15px;
      background: #f9f9f9;
      border-radius: 8px;
      margin-bottom: 20px;
      
      .section-title {
        font-weight: 500;
        margin-bottom: 10px;
        font-size: 14px;
      }
      
      .adjustment-row {
        display: flex;
        justify-content: space-between;
        font-size: 13px;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
      
      .price-increase {
        color: #07c160;
      }
      
      .price-decrease {
        color: #ee0a24;
      }
    }

    .order-total {
      display: flex;
      justify-content: space-between;
      font-size: 16px;
      font-weight: 500;
      margin-top: 20px;
      padding-top: 15px;
      border-top: 1px solid #f5f5f5;
      
      .total-amount {
        color: #ee0a24;
        font-weight: bold;
      }
    }

    .signature-area {
      margin-top: 50px;

      .signature-line {
        display: flex;
        font-size: 14px;

        .line {
          flex: 1;
          margin-left: 10px;
          color: #ccc;
        }
      }
    }
  }
  
  .preview-footer {
    padding-top: 15px;
    border-top: 1px solid #eee;
  }
}
</style> 